package com.woniu.realm;

import com.woniu.model.BmsPermission;
import com.woniu.model.BmsUser;
import com.woniu.service.IBmsUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Kevin Kwok
 * @create 2021-04-13 10:57
 */
@Component
@Slf4j
public class CustomRealm extends AuthorizingRealm {

    @Resource
    private IBmsUserService userService;

    /*授权*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        //获取登录用户
        BmsUser bmsUser = (BmsUser) principal.getPrimaryPrincipal();
        //创建权限对象
        SimpleAuthorizationInfo authorization = new SimpleAuthorizationInfo();
        try{
            //查询当前登录用户的所有权限
            List<BmsPermission> bmsPermissions = userService.queryAllUserPermission(bmsUser);
            for (BmsPermission permissions : bmsPermissions){
                //此时我们的权限对象已经得到当前用户的所有权限名字的集合
                authorization.addStringPermission(permissions.getPermissionName());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return authorization;
    }

    /*认证*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("进入了认证的方法……");
        /*认证开始*/
        String tel = (String) token.getPrincipal();
        System.out.println("开始认证……"+tel);
        BmsUser bmsUser = userService.queryUserByTel(tel);
        if (!ObjectUtils.isEmpty(bmsUser)) {
            return new SimpleAuthenticationInfo(bmsUser, bmsUser.getPassword(), ByteSource.Util.bytes(bmsUser.getSault()),this.getName());
        }
        return null;
    }
}
